from PIL import Image, ImageDraw

from modules.moc3_reader import Moc3Reader


def ttt(reader):
    vertex_cnt = reader.read_chunk_named('ArtMeshes.drawableVertexCount')
    am_idx = reader.read_chunk_named('ArtMeshes.keyformIndex')
    am_cnt = reader.read_chunk_named('ArtMeshes.keyformCount')
    amk = reader.read_chunk_named('ArtMeshKeyforms.keyformPositionIndex')
    poss = reader.read_chunk_named('KeyformPosition.xy', _format='<f')

    di_idx = reader.read_chunk_named('ArtMeshes.drawableIndexStart')
    di_cnt = reader.read_chunk_named('ArtMeshes.drawableIndexCount')
    di = reader.read_chunk_named('DrawableIndexes.index', unit_size=2, _format='<H')
    order = reader.read_chunk_named('ArtMeshKeyforms.drawOrder', _format='<f')

    ca_origin = (2400, 3090)
    ca_size = (4800, 6180)
    im = Image.new('RGBA', ca_size, (255, 255, 255, 0))
    draw = ImageDraw.Draw(im, 'RGBA')

    # binding and sort
    render_data = []
    for i, vc in enumerate(vertex_cnt):
        for k in range(am_cnt[i]):
            poss_idx_base = amk[am_idx[i] + k]
            _order = order[am_idx[i] + k]
            p_buf = []
            for j in range(vc):
                _x = poss[poss_idx_base + j * 2] + ca_origin[0]
                _y = poss[poss_idx_base + j * 2 + 1] + ca_origin[1]
                p_buf.append((_x, _y))

            frags = []
            for j in range(di_idx[i], di_idx[i] + di_cnt[i], 3):
                _px = p_buf[di[j]]
                _py = p_buf[di[j + 1]]
                _pz = p_buf[di[j + 2]]
                frags.append((_px, _py, _pz))

            render_data.append((_order, frags))
    render_data.sort(key=lambda x: x[0])

    for _, frags in render_data:
        for frag in frags:
            # draw.polygon(frag, (255, 168, 255, 255), (255, 255, 255, 255))
            draw.polygon(frag, None, (255, 255, 255, 255))

    # render

    # for i, vc in enumerate(vertex_cnt):
    #     for k in range(am_cnt[i]):
    #         poss_idx_base = amk[am_idx[i] + k]
    #         p_buf = []
    #         for j in range(vc):
    #             _x = poss[poss_idx_base + j * 2] + ca_origin[0]
    #             _y = poss[poss_idx_base + j * 2 + 1] + ca_origin[1]
    #             # im.putpixel((int(_x), int(_y)), (255, 255, 168, 255))
    #             draw.point((int(_x), int(_y)), (255, 255, 168, 255))
    #             p_buf.append((_x, _y))
    #
    #         for j in range(di_idx[i], di_idx[i] + di_cnt[i], 3):
    #             _px = p_buf[di[j]]
    #             _py = p_buf[di[j + 1]]
    #             _pz = p_buf[di[j + 2]]
    #             draw.polygon((_px, _py, _pz), (255, 168, 255, 255), (255, 255, 255, 255))

    im.show()


def main():
    source_dir = './chuixue_3/chuixue_3.moc3'
    reader = Moc3Reader(source_dir)
    ttt(reader)


if __name__ == '__main__':
    main()
